//
//  WBMainViewController.swift
//  迷你微博
//
//  Created by Json on 2020/2/3.
//  Copyright © 2020 Json. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        setupComposeButton()
    }
    
    
    /**
      portrait       :  竖屏
      landscape  ：横屏
     
      使用代码控制设备方向，好处：可以在需要横屏的时候单独处理
      设置支持的方向后，当前k的控制器及其子控制器都会遵守这个方向
      如果播放视频，通常是通过modal展现的
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    
    //私有控件，撰写按钮
    private lazy var composeButton:UIButton = UIButton.cz_imageButton(
        "tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")

    
    //撰写按钮
    //private能够保证方法私有化，
    //@objc允许这个函数运行时通过oc的消息机制被调用
    @objc private func composeStatus(){
        print("撰写按钮")
        
        //测试方向旋转
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.cz_random()
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
    }
}

//extension可以用来切分代码块
//可以把相近的函数放到一个extension中
//设置界面
extension WBMainViewController{
    
    //设置撰写按钮
    private func setupComposeButton(){
        tabBar.addSubview(composeButton)
        
        //计算按钮宽度
        let count = CGFloat(viewControllers!.count)
        let w = tabBar.bounds.width / count-1
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        //撰写按钮宽度
        //print("撰写按钮宽度 \(composeButton.bounds.width)")
        
        //按钮监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
    }
    
    //设置所有子控制器
    private func setupChildControllers(){
        /**
         很多应用程序界面创建都依赖网络json
         程序往服务器请求json配置->将配置保存在沙盒中->程序启动读取沙盒配置->如果沙盒中没有配置，就加载默认的json
         */
        
        // 获取沙盒路径 第三种方法，先从沙盒取，沙盒没有取本地
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        // 加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        // 判断data内是否有内容,如果没有，说明本地沙盒没有文件
        if data == nil {
            // 从 bundle 中加载 data
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        // 反序列化转换成数据
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]] else {
            return
        }
        
        
        /** 从 bundle 加载配置的 json 第二种方法
        guard let path = Bundle.main.path(forResource: "main.json", ofType: nil),
            let data = NSData(contentsOfFile: path),
            let array = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String : Any]] else {
            return
        }
        */
        
        /**
         配置信息第一种写法
        let array = [
            ["clsName":"WBHomeViewController","title":"首页","imageName":"home","visitorInfo": ["imageName":"","message":"关注一些人，回这里看看有什么惊喜"]],
            ["clsName":"WBMessageViewController","title":"消息","imageName":"message_center","visitorInfo": ["imageName":"visitordiscover_image_message","message":"登陆后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
            ["clsName":"UIViewController"],
            ["clsName":"WBDiscoverViewController","title":"发现","imageName":"discover","visitorInfo": ["imageName":"visitordiscover_image_message","message":"登陆后，最新，最热的微博尽在掌握，不再会于实事潮流擦肩而过"]],
            ["clsName":"WBProfileViewController","title":"我","imageName":"profile","visitorInfo": ["imageName":"visitordiscover_image_profile","message":"登陆后，你的微博，相册，个人资料会显示在这里，展示给别人"]]
        ]
         */
        
        // 测试数据格式
        //(array as NSArray).write(toFile: "/Users/json/Desktop/demo.plist", atomically: true)
        // 数组 -> json
        // options: [] 无格式的json
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (data as NSData).write(toFile: "/Users/json/Desktop/main.json", atomically: true)
        
        var arrayM = [UIViewController]()
        for dict in array {
            arrayM.append(controller(dict: dict as [String : AnyObject]))
        }
        
        viewControllers = arrayM
    }
    
    //使用字典创建一个子控制器
    private func controller(dict:[String:Any])->UIViewController{
        //取得字典内容
        //guard可选项
        // as? String类型强转
        guard  let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace+"."+clsName) as? WBBaseViewController.Type,
            let visitorDict = dict["visitorInfo"] as? [String: String]
        else {
            return UIViewController()
        }
        
        //创建视图控制器
        let vc = cls.init()
        vc.title = title
        
        //设置控制器访客信息字典
        vc.visitorInfoDictionary = visitorDict
        
        //设置图标
        vc.tabBarItem.image = UIImage(named: "tabbar_"+imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imageName+"_selected")?.withRenderingMode(.alwaysOriginal)
        
        //设置标题字体高亮
        vc.tabBarItem.setTitleTextAttributes(
            [NSAttributedString.Key.foregroundColor:UIColor.orange],
            for: .highlighted)
    
        //实例化导航栏控制器时，会调用push方法将rootVCt压栈
        let nav = WBNavigationController(rootViewController: vc)
        return nav
    }
}
